<template>
  <div id="userManagePage" class="min-h-screen bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100 transition-colors duration-300">
    <!-- 页面容器 -->
    <div class="container mx-auto px-4 py-6 max-w-7xl">
      <!-- 标题和操作区 -->
      <a-space style="margin-bottom: 10px">
        <a-button type="primary" href="/add_picture" target="_blank">创建图片</a-button>
        <a-button type="primary" href="/add_picture/batch" target="_blank" >批量创建图片</a-button>
      </a-space>


      <!-- 搜索表单卡片 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-5 mb-6 transition-all duration-300 hover:shadow-lg">
        <a-form layout="inline" :model="searchParams" @finish="doSearch" class="flex flex-wrap gap-4">
          <a-form-item label="关键词" name="searchText" class="flex-1 min-w-[200px]">
            <a-input
              v-model:value="searchParams.searchText"
              placeholder="从名称和简介搜索"
              allow-clear
              class="transition-all duration-200 focus:ring-2 focus:ring-primary/30"
            />
          </a-form-item>
          <a-form-item label="类型" name="category" class="flex-1 min-w-[200px]">
            <a-input
              v-model:value="searchParams.category"
              placeholder="请输入类型"
              allow-clear
              class="transition-all duration-200 focus:ring-2 focus:ring-primary/30"
            />
          </a-form-item>
          <a-form-item label="标签" name="tags" class="flex-1 min-w-[200px]">
            <a-select
              v-model:value="searchParams.tags"
              mode="tags"
              placeholder="请输入标签"
              style="min-width: 180px"
              allow-clear
              class="transition-all duration-200 focus:ring-2 focus:ring-primary/30"
            />
          </a-form-item>
          <a-form-item label="审核状态" name="reviewStatus" class="flex-1 min-w-[200px]">
            <a-select
              v-model:value="searchParams.reviewStatus"
              :options="PIC_REVIEW_STATUS_OPTIONS"
              placeholder="请选择审核状态"
              style="min-width: 180px"
              allow-clear
              class="transition-all duration-200 focus:ring-2 focus:ring-primary/30"
            />
          </a-form-item>
          <a-form-item class="self-end">
            <a-button
              type="primary"
              html-type="submit"
              class="transition-all duration-300 hover:shadow-lg px-6"
            >
              <i class="fa fa-search mr-2"></i>搜索
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 表格容器 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden transition-all duration-300 hover:shadow-lg">
        <a-table
          :columns="columns"
          :data-source="dataList"
          :pagination="pagination"
          @change="doTableChange"
          class="border-collapse"
          :row-class-name="rowClassName"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'url'">
              <div class="p-1 rounded border border-gray-200 dark:border-gray-700 hover:shadow-md transition-all duration-300">
                <a-image
                  :src="record.url"
                  :width="120"
                  preview
                  class="rounded"
                />
              </div>
            </template>
            <!-- 标签 -->
            <template v-if="column.dataIndex === 'tags'">
              <a-space wrap>
                <a-tag
                  v-for="tag in JSON.parse(record.tags || '[]')"
                  :key="tag"
                  class="transition-all duration-200 hover:scale-105"
                >
                  {{ tag }}
                </a-tag>
              </a-space>
            </template>
            <!-- 图片信息 -->
            <template v-if="column.dataIndex === 'picInfo'">
              <div class="space-y-1 text-sm">
                <div>格式：{{ record.picFormat }}</div>
                <div>宽度：{{ record.picWidth }}px</div>
                <div>高度：{{ record.picHeight }}px</div>
                <div>宽高比：{{ record.picScale }}</div>
                <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
              </div>
            </template>
            <!-- 审核信息 -->
            <template v-if="column.dataIndex === 'reviewMessage'">
              <div class="space-y-1 text-sm">
                <div>
                  审核状态：
                  <span
                    :class="statusClass(record.reviewStatus)"
                    class="px-2 py-0.5 rounded text-xs font-medium"
                  >
                    {{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}
                  </span>
                </div>
                <div>审核信息：{{ record.reviewMessage || '-' }}</div>
                <div>审核人：{{ record.reviewerId || '-' }}</div>
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'createTime'">
              {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-else-if="column.dataIndex === 'editTime'">
              {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space wrap>
                <a-button
                  v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
                  type="link"
                  @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
                  class="text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300 transition-colors"
                >
                  <i class="fa fa-check-circle mr-1"></i>通过
                </a-button>
                <a-button
                  v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
                  type="link"
                  danger
                  @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
                  class="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                >
                  <i class="fa fa-times-circle mr-1"></i>拒绝
                </a-button>
                <a-button
                  type="link"
                  :href="`/add_picture?id=${record.id}`"
                  target="_blank"
                  class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
                >
                  <i class="fa fa-edit mr-1"></i>编辑
                </a-button>
                <a-button
                  type="link"
                  danger
                  @click="doDelete(record.id)"
                  class="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 transition-colors"
                >
                  <i class="fa fa-trash mr-1"></i>删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {deletePictureUsingPost, doPictureReviewUsingPost, listPictureByPageUsingPost} from '@/api/pictureController.ts'
import {PIC_REVIEW_STATUS_ENUM, PIC_REVIEW_STATUS_MAP, PIC_REVIEW_STATUS_OPTIONS} from "@/constants/picture.ts";

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
    align: 'center',
  },
  {
    title: '图片',
    dataIndex: 'url',
    align: 'center',
  },
  {
    title: '名称',
    dataIndex: 'name',
    sorter: true,
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
    sorter: true,
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
    align: 'center',
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    sorter: true,
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
    sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]

// 数据
const dataList = ref([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
    showQuickJumper: true,
  }
})

// 获取数据
const fetchData = async () => {
  const res = await listPictureByPageUsingPost({
    ...searchParams,
    nullSpaceId: true,
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}


// 搜索处理
const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  // 处理排序
  if (page.sortField) {
    searchParams.sortField = page.sortField
    searchParams.sortOrder = page.sortOrder === 'ascend' ? 'asc' : 'desc'
  }
  fetchData()
}

// 删除处理
const doDelete = async (id: number) => {
  if (id == null) {
    message.error('id 为空')
    return
  }

  if (!confirm('确定要删除这张图片吗？此操作不可恢复。')) {
    return
  }

  const deleteResponse = await deletePictureUsingPost({ id })
  if (deleteResponse.data.data && deleteResponse.data.code === 0) {
    await fetchData()
    message.success('删除成功')
  } else {
    message.error('删除失败：' + (deleteResponse.data.message || '未知错误'))
  }
}

// 审核处理
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const action = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '通过' : '拒绝'
  if (!confirm(`确定要${action}这张图片吗？`)) {
    return
  }

  const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS
    ? '管理员操作通过'
    : '管理员操作拒绝'

  try {
    const res = await doPictureReviewUsingPost({
      id: record.id,
      reviewStatus,
      reviewMessage,
    })
    if (res.data.code === 0) {
      message.success(`审核${action}成功`)
      fetchData()
    } else {
      message.error(`审核${action}失败：${res.data.message || '未知错误'}`)
    }
  } catch (error) {
    message.error(`审核${action}失败：网络错误`)
  }
}

// 行样式
const rowClassName = (record: any, index: number) => {
  return index % 2 === 0 ? 'bg-gray-50 dark:bg-gray-800/50' : ''
}

// 审核状态样式
const statusClass = (status: number) => {
  switch(status) {
    case PIC_REVIEW_STATUS_ENUM.PENDING:
      return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400'
    case PIC_REVIEW_STATUS_ENUM.PASS:
      return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
    case PIC_REVIEW_STATUS_ENUM.REJECT:
      return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
    default:
      return 'bg-gray-100 text-gray-800 dark:bg-gray-700/30 dark:text-gray-400'
  }
}

// 页面加载时请求数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
/* 表格样式优化 */
:deep(.ant-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f5f7fa;
  dark-mode: #1f2937;
  font-weight: 600;
  text-align: left;
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  transition: background-color 0.2s ease;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f9fafb !important;
  dark-mode: #111827 !important;
}

/* 表单元素优化 */
:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

/* 按钮样式优化 */
:deep(.ant-btn) {
  border-radius: 6px;
  transition: all 0.2s ease;
}

:deep(.ant-btn-primary) {
  background-color: #1677ff;
  border-color: #1677ff;
}

:deep(.ant-btn-primary:hover) {
  background-color: #0f62d9;
  border-color: #0f62d9;
}

/* 标签样式优化 */
:deep(.ant-tag) {
  border-radius: 4px;
  padding: 2px 8px;
  margin: 2px 0;
}

/* 图片样式 */
:deep(.ant-image-img) {
  object-fit: cover;
  border-radius: 4px;
  transition: transform 0.3s ease;
}

:deep(.ant-image-img:hover) {
  transform: scale(1.03);
}

/* 响应式优化 */
@media (max-width: 768px) {
  :deep(.ant-table) {
    font-size: 12px;
  }

  :deep(.ant-table-tbody > tr > td) {
    padding: 8px;
  }

  .ant-upload-select-picture-card i {
    font-size: 24px;
  }
}
</style>
